package tech.wetech.admin3.controller;

import cn.hutool.json.JSONObject;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import tech.wetech.admin3.sys.exception.AooUserException;
import tech.wetech.admin3.sys.model.AooUser;
import tech.wetech.admin3.sys.model.AooVirtualMan;
import tech.wetech.admin3.sys.model.DID;
import tech.wetech.admin3.sys.service.*;
import tech.wetech.admin3.util.*;

import java.util.*;


@RestController
@RequestMapping("/Digital")
public class AooVirtualManController {
  private DIDCreateUtil didCreateUtil;
  private AooVirtualManService virtualManService;
  private HashUtil hashUtil;
  private LianduAPIUtils lianduAPIUtil;

  private AooPhoneCodeService phoneCodeService;

  public AooVirtualManController(
    DIDCreateUtil didCreateUtil,
    AooVirtualManService virtualManService,
    HashUtil hashUtil,
    LianduAPIUtils lianduAPIUtil,
    AooPhoneCodeService phoneCodeService
  ) {
    this.didCreateUtil = didCreateUtil;
    this.virtualManService = virtualManService;
    this.hashUtil = hashUtil;
    this.lianduAPIUtil = lianduAPIUtil;
    this.phoneCodeService = phoneCodeService;
  }

  @PostMapping("/virtualMan")
  public ResponseEntity<?> createVirtualMan(
    @RequestParam("owner") String owner,
    @RequestParam("ownerIdNo") String ownerIdNo,
    @RequestParam("email") String email,
    @RequestParam("digitalName") String digitalName,
    @RequestParam("mobile") String mobile,
    @RequestParam("vericode") String vericode,
    @RequestParam(value = "feature", required = false) String feature,
    @RequestParam(value = "purpose", required = false) String purpose,
    @RequestParam("images") MultipartFile[] images,
    @RequestParam(value = "modelFiles", required = false) MultipartFile[] modelFiles,
    @RequestParam(value = "signFileUrl", required = false) String signFileUrl
  ) {
    try {
      AooVirtualMan virtualMan = virtualManService.createVirtualMan(owner, ownerIdNo, email, digitalName, mobile, vericode,
        feature, purpose, modelFiles, images, signFileUrl);
      return ResponseEntity.ok(new CustomResponse.r1("提交成功", true, virtualMan));
    } catch (AooUserException e) {
      return ResponseEntity.ok(new CustomResponse.r1<>(e.getMessage(), false, null));
    }
  }

  @Transactional
  @PutMapping("/reset/status-virtualman")
  public ResponseEntity<?> resetStatus(
    @RequestParam("uuid") UUID uuid,
    @RequestParam("newStatus") Integer newStatus,
    @RequestParam(value = "checkDesc", required = false) String checkDesc
  ) {
    // 对newStatus的验证
    if (newStatus < 1 || newStatus > 3) {
      return ResponseEntity.badRequest().body(new CustomResponse.r1("状态值无效，只能为1, 2 或3", false, null));
    }

    boolean flag = virtualManService.resetStatus(uuid, newStatus, checkDesc);
    if (flag) {
      if (newStatus == 2) {  // 审核通过,创建DID
        AooVirtualMan virtualMan = virtualManService.findByUuid(uuid);
        String digitalName = virtualMan.getDigitalName();
        String owner = virtualMan.getOwner();
        String imageUrls = virtualMan.getImageUrls();
        String imageHashes = virtualMan.getImageHashes();
        String modelFileUrls = virtualMan.getModelFileUrls();
        String modelFileHashes = virtualMan.getModelFileHashes();

//        DIDCreateUtil didCreateUtil = new DIDCreateUtil(didService);
        DID did = didCreateUtil.createDID("x", digitalName, owner, imageUrls, imageHashes, modelFileUrls, modelFileHashes);

        String serial = did.getSerial();
        String didNo = did.getDidNo();
        virtualMan.setSerial(serial);
        virtualMan.setDidNo(didNo);

        String hashV = hashUtil.getStringHash(serial);
        int timeStamp = (int) (System.currentTimeMillis() / 1000);

        Map<String, Object> datainfo = new HashMap<>();
        datainfo.put("name", did.getName());
        datainfo.put("type", did.getType());
        datainfo.put("serial", did.getSerial());
        datainfo.put("didNo", did.getDidNo());
        datainfo.put("ukey", did.getUkey());
        datainfo.put("txhash", did.getTxhash());

        JSONObject res_saveAuth = lianduAPIUtil.saveAuth(hashV, timeStamp, datainfo.toString()).join();
        System.out.println("res_saveAuth---" + res_saveAuth);

        if (res_saveAuth.getStr("txhash") != null) {
          did.setTxhash_saveAuth(res_saveAuth.getStr("txhash"));
        } else {
          return ResponseEntity.ok(new CustomResponse.r1("did角色已创建，但上链存证失败", true, did));
        }

        return ResponseEntity.ok(new CustomResponse.r1("审核通过，已创建DID角色", true, did));
      } else if (newStatus == 3) {
        return ResponseEntity.ok(new CustomResponse.r1("审核驳回", true, null));
      } else {
        return ResponseEntity.ok(new CustomResponse.r1("审核中", true, null));
      }
    } else {
      return ResponseEntity.ok(new CustomResponse.r1("未找到该审核资料,请检查uuid是否正确", false, null));
    }
  }

  @Transactional
  @PutMapping("/admin/reset/status-virtualman")
  public ResponseEntity<?> admin_resetStatus(
    @RequestParam("uuid") UUID uuid,
    @RequestParam("newStatus") Integer newStatus,
    @RequestParam(value = "checkDesc", required = false) String checkDesc,
    @RequestParam("vericode") String vericode
  ) {
    boolean flag_admin = phoneCodeService.admin_VerifyCode(vericode);
    if (!flag_admin) {
      return ResponseEntity.ok(new CustomResponse.r1("admin 验证码错误或已过期", false, null));
    }

    // 对newStatus的验证
    if (newStatus < 1 || newStatus > 3) {
      return ResponseEntity.badRequest().body(new CustomResponse.r1("状态值无效，只能为1, 2 或3", false, null));
    }

    boolean flag = virtualManService.resetStatus(uuid, newStatus, checkDesc);
    if (flag) {
      if (newStatus == 2) {  // 审核通过,创建DID
        AooVirtualMan virtualMan = virtualManService.findByUuid(uuid);
        String digitalName = virtualMan.getDigitalName();
        String owner = virtualMan.getOwner();
        String imageUrls = virtualMan.getImageUrls();
        String imageHashes = virtualMan.getImageHashes();
        String modelFileUrls = virtualMan.getModelFileUrls();
        String modelFileHashes = virtualMan.getModelFileHashes();

//        DIDCreateUtil didCreateUtil = new DIDCreateUtil(didService);
        DID did = didCreateUtil.createDID("x", digitalName, owner, imageUrls, imageHashes, modelFileUrls, modelFileHashes);

        String serial = did.getSerial();
        String didNo = did.getDidNo();
        virtualMan.setSerial(serial);
        virtualMan.setDidNo(didNo);

        String hashV = hashUtil.getStringHash(serial);
        int timeStamp = (int) (System.currentTimeMillis() / 1000);

        Map<String, Object> datainfo = new HashMap<>();
        datainfo.put("name", did.getName());
        datainfo.put("type", did.getType());
        datainfo.put("serial", did.getSerial());
        datainfo.put("didNo", did.getDidNo());
        datainfo.put("ukey", did.getUkey());
        datainfo.put("txhash", did.getTxhash());

        JSONObject res_saveAuth = lianduAPIUtil.saveAuth(hashV, timeStamp, datainfo.toString()).join();
        System.out.println("res_saveAuth---" + res_saveAuth);

        if (res_saveAuth.getStr("txhash") != null) {
          did.setTxhash_saveAuth(res_saveAuth.getStr("txhash"));
        } else {
          return ResponseEntity.ok(new CustomResponse.r1("did角色已创建，但上链存证失败", true, did));
        }

        return ResponseEntity.ok(new CustomResponse.r1("审核通过，已创建DID角色", true, did));
      } else if (newStatus == 3) {
        return ResponseEntity.ok(new CustomResponse.r1("审核驳回", true, null));
      } else {
        return ResponseEntity.ok(new CustomResponse.r1("审核中", true, null));
      }
    } else {
      return ResponseEntity.ok(new CustomResponse.r1("未找到该审核资料,请检查uuid是否正确", false, null));
    }
  }

  @Transactional
  @PutMapping("/admin/update/paid")
  public AooVirtualMan admin_update_virtualMan(
    @RequestParam("uuid") UUID uuid,
    @RequestParam("key") String key,
    @RequestParam("value") boolean value,
    @RequestParam("vericode") String vericode
  ) {
    return virtualManService.admin_update(uuid, key, value, vericode);
  }

  @GetMapping("/getall/virtualman")
  public ResponseEntity<?> getAllData(
    @RequestParam("page") int page,
    @RequestParam("size") int size,
    @RequestParam(value = "paid", required = false) Boolean paid
  ) {
    List<?> data;
    if (Boolean.TRUE.equals(paid)) {
      data = virtualManService.findByPaid(true);
    } else {
      data = virtualManService.getAllData();
    }

    int total = data.size();
    int start = page * size;
    int end = Math.min(start + size, total);
    List<Object> paginatedList;

    if (start < total) {
      paginatedList = new ArrayList<>(data.subList(start, end));
    } else {
      paginatedList = new ArrayList<>();
    }

    Map<String, Object> result = new HashMap<>();
    result.put("page", page);
    result.put("size", size);
    result.put("total", total);
    result.put("record", paginatedList);
    return ResponseEntity.ok(new CustomResponse.r1("ok", true, result));
  }

  @GetMapping("/getbyemail/virtualman")
  public ResponseEntity<?> getByEmail(
    @RequestParam("email") String email
  ) {
    List data = virtualManService.findByEmail(email);
    return ResponseEntity.ok(new CustomResponse.r1("ok", true, data));
  }

}
